package com.hospitalsystem.controller;

import com.hospitalsystem.entity.*;
import com.hospitalsystem.service.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Arrange)表控制层
 *
 * @author makejava
 * @since 2024-12-28 19:24:16
 */
@RestController
@RequestMapping("arrange")
public class ArrangeController {
    /**
     * 服务对象
     */
    @Resource
    private ArrangeService arrangeService;

    @Resource
    private PatientService patientService;

    @Resource
    private DoctorService doctorService;

    @Resource
    private MedicalRecordService medicalRecordService;

    @Resource
    private CheckListService checkListService;

    /**
     * 分页查询
     *
     * @param arrange 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Arrange>> queryByPage(Arrange arrange, PageRequest pageRequest) {
        return ResponseEntity.ok(this.arrangeService.queryByPage(arrange, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param arrangeId
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Arrange> queryById(@PathVariable("id")String arrangeId) {
        return ResponseEntity.ok(this.arrangeService.queryById(arrangeId));
    }

    /**
     * 新增数据
     *
     * @param arrange 实体
     * @return 新增结果
     */
    @PostMapping("/add")
    public ResponseEntity<Arrange> add(@RequestParam String pId,
                                       @RequestParam String arrangeTime,
                                       @RequestParam String department) throws ParseException {
        return ResponseEntity.ok(this.arrangeService.insert(pId, arrangeTime, department));
    }

    /**
     * 查询id是否存在
     *
     * @param arrangeId
     * @return 是否存在
     */
    @GetMapping("/exist/{id}")
    public ResponseEntity<Map<String, Boolean>> existId(@PathVariable("id")String arrangeId) {
        boolean exists = this.arrangeService.existId(arrangeId);
        Map<String, Boolean> response = new HashMap<>();
        response.put("exist",exists);
        return ResponseEntity.ok(response);
    }

    /**
     * 编辑数据
     *
     * @param arrange 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Arrange> edit(Arrange arrange) {
        return ResponseEntity.ok(this.arrangeService.update(arrange));
    }

    /**
     * 删除数据
     *
     * @param arrangeId
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(String arrangeId) {
        return ResponseEntity.ok(this.arrangeService.deleteById(arrangeId));
    }

    /**
     * 修改是否就诊
     *
     * @param idCard
     * @param dId
     * @return 删除是否成功
     */
    @PostMapping("/updateIfFinish")
    public ResponseEntity<Boolean> updateIfFinish(String idCard,String dId) {
        return ResponseEntity.ok(this.arrangeService.updateIfFinish(idCard,dId));
    }

    /**
     * 根据患者id查询所有挂号记录
     *
     * @param pId
     * @return 挂号记录List
     */
    @GetMapping("/findArrangeByPId")
    public ResponseEntity<List<Arrange>> findArrangeByPId(String pId) {
        return ResponseEntity.ok(this.arrangeService.findArrangeByPId(pId));
    }

    /**
     * 根据患者id查询所有挂号记录
     *
     * @param pId
     * @return 挂号记录List,前面还有多少人
     */
    @GetMapping("/findArrangeByPId2")
    public ResponseEntity<ArrangeResponse> findArrangeByPId2(String pId) {
        return ResponseEntity.ok(this.arrangeService.findArrangeByPId2(pId));
    }

    /**
     * 根据arrangeId修改ifPay
     *
     * @param arrangeId
     * @return 修改是否成功
     */
    @GetMapping("/updateIfPay")
    public ResponseEntity<Boolean> updateIfPay(String arrangeId) {
        return ResponseEntity.ok(this.arrangeService.updateIfPay(arrangeId));
    }

    /**
     * 根据arrangeId获取病历、患者、医生、开药单
     *
     * @param arrangeId
     * @return
     */
    @GetMapping("/getPatientRecordByArrangeId")
    public ResponseEntity<Map<String, Object>> getPatientRecordByArrangeId(String arrangeId) {
        PatientRecord patientRecord = this.arrangeService.getPatientRecordByArrangeId(arrangeId);
        if (patientRecord == null) {
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("message", "没有对应的病历");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseMap);
        }
        Arrange arrange = this.arrangeService.queryById(arrangeId);
        if (arrange == null) {
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("message", "未找到挂号单");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseMap);
        }
        String pId = arrange.getPId();
        Patient patient = this.patientService.queryById(pId);
        if (patient == null) {
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("message", "未找到病人");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseMap);
        }
        String dId = arrange.getDId();
        Doctor doctor = this.doctorService.queryById(dId);
        if (doctor == null) {
            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("message", "未找到医生");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(responseMap);
        }
        String pRId = patientRecord.getPRId();
        MedicalRecord medicalRecord = this.arrangeService.getMedicalRecordByPRId(pRId);
        List<CheckList> checkLists = new ArrayList<>();
        List<Map<String, Object>> drugsWithQuantity = new ArrayList<>();
        if (medicalRecord == null) {
            // 返回空的 checkLists 和 drugsWithQuantity
            PatientRecordResponse response = new PatientRecordResponse(null, doctor, patient, patientRecord, checkLists, drugsWithQuantity);

            Map<String, Object> responseMap = new HashMap<>();
            responseMap.put("data", response);
            responseMap.put("message", "未找到开药单信息");
            responseMap.put("status", 200);  // 依然返回成功状态，表明请求被成功处理

            return ResponseEntity.ok(responseMap);
        }
        else{
            // 将 check_list 字段按换行符分割成检查项列表
            String checkListStr = medicalRecord.getCheckList();
            String[] checkListItems = checkListStr.split("\n");

            // 查询 check_list 表，找到每个检查项
            for (String item : checkListItems) {
                // 查询 check_list 表
                CheckList checkList = this.arrangeService.getCheckListByName(item.trim());
                if (checkList != null) {
                    checkLists.add(checkList);
                }
            }

            // 将 drug_list 字段按换行符分割成药品项列表
            String drugListStr = medicalRecord.getDrugList();
            String[] drugListItems = drugListStr.split("\n");

            // 查询 drug 表，找到每个药品
            for (String item : drugListItems) {
                // 拆分药品名称和数量，假设是 "药品名称 数量" 的格式
                String[] parts = item.trim().split("\\s+");  // 使用正则匹配一个或多个空格
                if (parts.length != 2) {
                    continue;  // 如果格式不正确则跳过
                }

                String drugName = parts[0];  // 药品名称
                int quantity = Integer.parseInt(parts[1]);  // 药品数量

                // 查询 drug 表获取药品信息
                Drug drug = this.arrangeService.getDrugByName(drugName);
                if (drug != null) {
                    // 将药品信息和数量一并封装返回
                    Map<String, Object> drugInfo = new HashMap<>();
                    drugInfo.put("name", drug.getName());
                    drugInfo.put("quantity", quantity);
                    drugInfo.put("details", drug);  // 可以将药品详细信息也返回
                    drugsWithQuantity.add(drugInfo);
                }
            }

        }

        PatientRecordResponse response = new PatientRecordResponse(medicalRecord,doctor,patient,patientRecord, checkLists, drugsWithQuantity);

        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("data",response);
        responseMap.put("message","success");
        responseMap.put("status",200);

        return ResponseEntity.ok(responseMap);
    }

}

